package cn.zmwh.manage.admin.modules.upms.service;

import cn.zmwh.common.core.constants.Constants;
import cn.zmwh.manage.admin.modules.upms.mapper.SysMenuMapper;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysMenu;
import cn.zmwh.manage.admin.modules.upms.pojo.vo.SysMenuNode;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-11
 */
@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {


    public List<SysMenuNode> treeList(Long uid, String userName) {
        List<SysMenu> menuList;
        if (Constants.LTY.equals(userName)) {
            menuList = baseMapper.selectList(Wrappers.<SysMenu>lambdaQuery().ne(SysMenu::getMenuType, Constants.HT_URL));
        } else {
            menuList = baseMapper.findByFrontType(uid);
        }
        List<SysMenuNode> result = menuList.stream()
                .filter(menu -> menu.getPid().equals(0L))
                .map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
        return result;
    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性
     */
    private SysMenuNode covertMenuNode(SysMenu menu, List<SysMenu> menuList) {
        SysMenuNode node = new SysMenuNode();
        BeanUtils.copyProperties(menu, node);
        List<SysMenuNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getPid().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
